package Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import model.Ponto;

public class PontoDao {

	static final  String JDBC_DRIVER = "org.postgresql.Driver";
	static final String DATABASE_URL = "jdbc:postgresql://localhost:5432/chat?autoreconnect=true";
	Connection connection = null;
	Statement statement = null;
	String user = "postgres";
	String password = "root";
	static int id = 3 ;

	public PontoDao(){
		try {

			Class.forName(JDBC_DRIVER);

			connection = DriverManager.getConnection(DATABASE_URL, user, password);

		} catch (SQLException sql) {
			sql.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}		


	}

	public boolean insert(Ponto ponto){
		try {
			String sql = "INSERT INTO PONTO (descricao, latitude, longitude)" +
			"VALUES (?, ?, ?)" ;

			PreparedStatement pstmt  = connection.prepareStatement(sql);
			pstmt.setString(1, ponto.getDescricao());
			pstmt.setDouble(2, ponto.getLatitude());
			pstmt.setDouble(3, ponto.getLongitude());
			
			pstmt.executeUpdate();
			pstmt.close();
			
			return true;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}
	
	public List<Ponto> listar() {
		List<Ponto> pontos = new ArrayList<Ponto>();
		
		try {
			
			Statement stmt = connection.createStatement();
			
			String select = "SELECT * FROM ponto ORDER BY descricao ASC";
			ResultSet rs = stmt.executeQuery(select);
			
			while (rs.next()){
				Ponto ponto = new Ponto();
				
				ponto.setDescricao(rs.getString("descricao"));
				ponto.setLatitude(rs.getDouble("latitude"));
				ponto.setLongitude(rs.getDouble("longitude"));
				
				pontos.add(ponto);
			}
            
						
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return pontos;
		
	}
	
	public void finaliza(){
		try {
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

}
